<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能电商搜索系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        :root {
            --primary-color: #ff5000;
            --secondary-color: #f5f5f5;
            --text-dark: #333;
            --text-light: #666;
            --border-color: #e0e0e0;
            --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        body {
            background: linear-gradient(135deg, #f9f9f9, #f0f2f5);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            text-align: center;
            margin: 30px 0;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            margin-bottom: 20px;
        }

        .logo i {
            font-size: 36px;
            color: var(--primary-color);
        }

        h1 {
            font-size: 32px;
            color: var(--text-dark);
            margin-bottom: 5px;
            background: linear-gradient(90deg, #ff5000, #ff8400);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .subtitle {
            color: var(--text-light);
            font-size: 16px;
            margin-bottom: 30px;
        }

        .search-container {
            position: relative;
            max-width: 800px;
            margin: 0 auto 40px;
        }

        .search-box {
            display: flex;
            border-radius: 50px;
            overflow: hidden;
            box-shadow: var(--shadow);
            transition: all 0.3s ease;
        }

        .search-box:focus-within {
            box-shadow: 0 6px 18px rgba(255, 80, 0, 0.25);
        }

        #search-input {
            flex: 1;
            padding: 18px 25px;
            font-size: 18px;
            border: none;
            outline: none;
            background: white;
        }

        #search-button {
            padding: 0 35px;
            background: var(--primary-color);
            color: white;
            border: none;
            cursor: pointer;
            font-size: 18px;
            transition: background 0.3s;
        }

        #search-button:hover {
            background: #ff3a00;
        }

        .suggestions-container {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border-radius: 12px;
            margin-top: 10px;
            box-shadow: var(--shadow);
            z-index: 100;
            max-height: 400px;
            overflow-y: auto;
            display: none;
        }

        .suggestion-section {
            padding: 15px 0;
            border-bottom: 1px solid var(--border-color);
        }

        .section-title {
            padding: 8px 20px;
            font-size: 15px;
            color: var(--text-light);
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .suggestion-list {
            list-style: none;
        }

        .suggestion-item {
            padding: 12px 20px 12px 55px;
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: background 0.2s;
            position: relative;
        }

        .suggestion-item:hover {
            background: var(--secondary-color);
        }

        .suggestion-item i {
            position: absolute;
            left: 20px;
            font-size: 18px;
            color: var(--text-light);
        }

        .suggestion-text {
            font-size: 16px;
        }

        .suggestion-highlight {
            color: var(--primary-color);
            font-weight: 600;
        }

        .suggestion-count {
            margin-left: auto;
            background: #f0f2f5;
            color: var(--text-light);
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
        }

        .results-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .product-card {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            transition: all 0.3s ease;
            box-shadow: var(--shadow);
            position: relative;
        }

        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .product-badge {
            position: absolute;
            top: 12px;
            left: 12px;
            background: var(--primary-color);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            z-index: 10;
        }

        .product-image-container {
            height: 220px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #fafafa;
            overflow: hidden;
        }

        .product-image {
            max-width: 80%;
            max-height: 80%;
            object-fit: contain;
            transition: transform 0.3s;
        }

        .product-card:hover .product-image {
            transform: scale(1.05);
        }

        .product-info {
            padding: 18px;
        }

        .product-title {
            font-weight: 600;
            font-size: 16px;
            color: var(--text-dark);
            margin-bottom: 12px;
            height: 44px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }

        .product-price {
            color: var(--primary-color);
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .product-meta {
            display: flex;
            justify-content: space-between;
            color: var(--text-light);
            font-size: 14px;
        }

        .product-rating {
            color: #ffb400;
        }

        .empty-results {
            grid-column: 1 / -1;
            text-align: center;
            padding: 50px 0;
            color: var(--text-light);
        }

        .empty-results i {
            font-size: 60px;
            margin-bottom: 20px;
            color: #e0e0e0;
        }

        .empty-results h3 {
            font-size: 24px;
            margin-bottom: 10px;
            color: var(--text-dark);
        }

        .search-history {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-top: 20px;
            justify-content: center;
        }

        .history-tag {
            background: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            color: var(--text-light);
            cursor: pointer;
            transition: all 0.2s;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }

        .history-tag:hover {
            background: var(--primary-color);
            color: white;
            box-shadow: 0 4px 8px rgba(255, 80, 0, 0.2);
        }

        footer {
            text-align: center;
            padding: 20px 0;
            color: var(--text-light);
            font-size: 14px;
            border-top: 1px solid var(--border-color);
            margin-top: 40px;
        }

        @media (max-width: 768px) {
            .search-box {
                border-radius: 12px;
            }

            #search-input {
                padding: 15px 20px;
            }

            #search-button {
                padding: 0 25px;
            }

            .results-container {
                grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
                gap: 15px;
            }

            .product-image-container {
                height: 180px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="logo">
                <i class="fas fa-shopping-bag"></i>
            </div>
            <h1>智能电商搜索系统</h1>
        </header>

        <div class="search-container">
            <div class="search-box">
                <input type="text" id="search-input" placeholder="搜索商品名称、品牌、类别..." autocomplete="off">
                <button id="search-button"><i class="fas fa-search"></i> 搜索</button>
            </div>

            <div class="suggestions-container" id="suggestions-container">
                <!-- 历史搜索 -->
                <div class="suggestion-section">
                    <div class="section-title">
                        <i class="fas fa-history"></i>
                        <span>历史搜索</span>
                    </div>
                    <ul class="suggestion-list" id="history-list">
                        <!-- 历史记录将通过JS动态添加 -->
                    </ul>
                </div>

                <!-- 热门搜索 -->
                <div class="suggestion-section">
                    <div class="section-title">
                        <i class="fas fa-fire"></i>
                        <span>热门搜索</span>
                    </div>
                    <ul class="suggestion-list" id="popular-list">
                        <!-- 热门搜索将通过JS动态添加 -->
                    </ul>
                </div>

                <!-- 实时建议 -->
                <div class="suggestion-section">
                    <div class="section-title">
                        <i class="fas fa-lightbulb"></i>
                        <span>搜索建议</span>
                    </div>
                    <ul class="suggestion-list" id="suggestions-list">
                        <!-- 实时建议将通过JS动态添加 -->
                    </ul>
                </div>

                <!-- 类别建议 -->
                <div class="suggestion-section">
                    <div class="section-title">
                        <i class="fas fa-tags"></i>
                        <span>热门分类</span>
                    </div>
                    <ul class="suggestion-list" id="categories-list">
                        <!-- 类别建议将通过JS动态添加 -->
                    </ul>
                </div>
            </div>
        </div>

        <div class="search-history" id="search-history">
            <!-- 历史搜索标签将通过JS动态添加 -->
        </div>

        <div class="results-container" id="results-container">
            <!-- 初始状态显示提示 -->
            <div class="empty-results">
                <i class="fas fa-search"></i>
                <h3>开始您的搜索之旅</h3>
                <p>输入关键词，探索海量优质商品</p>
            </div>
        </div>

        <footer>
            <p>© 2025 智能电商搜索系统 | 基于深度学习与用户行为分析</p>
        </footer>
    </div>

    <script>
        // DOM元素
        const searchInput = document.getElementById('search-input');
        const searchButton = document.getElementById('search-button');
        const suggestionsContainer = document.getElementById('suggestions-container');
        const historyList = document.getElementById('history-list');
        const popularList = document.getElementById('popular-list');
        const suggestionsList = document.getElementById('suggestions-list');
        const categoriesList = document.getElementById('categories-list');
        const resultsContainer = document.getElementById('results-container');
        const searchHistoryContainer = document.getElementById('search-history');

        // 模拟数据 - 在实际应用中这些数据应从后端API获取
        const popularSearches = [
            {text: "智能手机", count: 15420},
            {text: "笔记本电脑", count: 12045},
            {text: "蓝牙耳机", count: 9820},
            {text: "运动鞋", count: 8750},
            {text: "夏季连衣裙", count: 7640}
        ];

        const categories = [
            {text: "手机数码", icon: "mobile-alt"},
            {text: "电脑办公", icon: "laptop"},
            {text: "家用电器", icon: "tv"},
            {text: "服装鞋包", icon: "tshirt"},
            {text: "美妆护肤", icon: "spa"},
            {text: "食品生鲜", icon: "apple-alt"},
            {text: "运动户外", icon: "bicycle"},
            {text: "母婴玩具", icon: "baby"}
        ];

        // 用户搜索历史（存储在localStorage中）
        let userSearchHistory = JSON.parse(localStorage.getItem('searchHistory')) || [];

        // 初始化页面
        function initPage() {
            renderPopularSearches();
            renderCategories();
            renderSearchHistoryTags();
        }

        // 渲染热门搜索
        function renderPopularSearches() {
            popularList.innerHTML = popularSearches.map((item, index) => `
                <li class="suggestion-item">
                    <i class="fas fa-${index < 3 ? 'fire' : 'search'}"></i>
                    <span class="suggestion-text">${item.text}</span>
                    <span class="suggestion-count">${formatCount(item.count)}</span>
                </li>
            `).join('');

            // 添加事件监听
            document.querySelectorAll('#popular-list .suggestion-item').forEach(item => {
                const text = item.querySelector('.suggestion-text').textContent;
                item.addEventListener('click', () => performSearch(text));
            });
        }

        // 渲染类别建议
        function renderCategories() {
            categoriesList.innerHTML = categories.map(category => `
                <li class="suggestion-item">
                    <i class="fas fa-${category.icon}"></i>
                    <span class="suggestion-text">${category.text}</span>
                </li>
            `).join('');

            // 添加事件监听
            document.querySelectorAll('#categories-list .suggestion-item').forEach(item => {
                const text = item.querySelector('.suggestion-text').textContent;
                item.addEventListener('click', () => performSearch(text));
            });
        }

        // 渲染历史搜索列表
        function renderHistoryList() {
            historyList.innerHTML = userSearchHistory.slice(0, 5).map(item => `
                <li class="suggestion-item">
                    <i class="fas fa-history"></i>
                    <span class="suggestion-text">${item}</span>
                </li>
            `).join('');

            // 添加事件监听
            document.querySelectorAll('#history-list .suggestion-item').forEach(item => {
                const text = item.querySelector('.suggestion-text').textContent;
                item.addEventListener('click', () => performSearch(text));
            });
        }

        // 渲染历史搜索标签
        function renderSearchHistoryTags() {
            if (userSearchHistory.length === 0) {
                searchHistoryContainer.innerHTML = '<p>暂无搜索历史</p>';
                return;
            }

            searchHistoryContainer.innerHTML = userSearchHistory.slice(0, 10).map(item => `
                <div class="history-tag">${item}</div>
            `).join('');

            // 添加事件监听
            document.querySelectorAll('.history-tag').forEach(tag => {
                tag.addEventListener('click', () => {
                    searchInput.value = tag.textContent;
                    performSearch(tag.textContent);
                });
            });
        }

        // 添加搜索历史
        function addToSearchHistory(query) {
            if (!query.trim()) return;

            // 移除重复项
            userSearchHistory = userSearchHistory.filter(item => item.toLowerCase() !== query.toLowerCase());

            // 添加到开头
            userSearchHistory.unshift(query);

            // 限制历史记录数量
            if (userSearchHistory.length > 10) {
                userSearchHistory = userSearchHistory.slice(0, 10);
            }

            // 保存到localStorage
            localStorage.setItem('searchHistory', JSON.stringify(userSearchHistory));

            // 更新UI
            renderHistoryList();
            renderSearchHistoryTags();
        }

        // 格式化数字（如10000转为1万）
        function formatCount(count) {
            if (count >= 10000) {
                return (count / 10000).toFixed(1) + '万';
            }
            return count;
        }

        // 获取搜索建议
        async function getSearchSuggestions(query) {
            if (!query.trim()) {
                suggestionsContainer.style.display = 'block';
                renderHistoryList();
                suggestionsList.innerHTML = '<li class="suggestion-item"><i class="fas fa-info-circle"></i><span>继续输入获取更多建议</span></li>';
                return;
            }

            try {
                // 在实际应用中这里应该调用后端API
                // const response = await fetch(`/suggest?q=${encodeURIComponent(query)}`);
                // const suggestions = await response.json();

                // 模拟API响应
                const mockSuggestions = [
                    {text: query + " 手机", count: Math.floor(Math.random() * 1000) + 500},
                    {text: query + " 新款", count: Math.floor(Math.random() * 800) + 300},
                    {text: query + " 官方旗舰店", count: Math.floor(Math.random() * 600) + 200},
                    {text: query + " 正品", count: Math.floor(Math.random() * 400) + 100},
                    {text: query + " 优惠", count: Math.floor(Math.random() * 300) + 50}
                ];

                // 高亮匹配部分
                suggestionsList.innerHTML = mockSuggestions.map(item => {
                    const index = item.text.toLowerCase().indexOf(query.toLowerCase());
                    if (index >= 0) {
                        const before = item.text.substring(0, index);
                        const match = item.text.substring(index, index + query.length);
                        const after = item.text.substring(index + query.length);

                        return `
                            <li class="suggestion-item">
                                <i class="fas fa-search"></i>
                                <span class="suggestion-text">
                                    ${before}<span class="suggestion-highlight">${match}</span>${after}
                                </span>
                                <span class="suggestion-count">${formatCount(item.count)}</span>
                            </li>
                        `;
                    }
                    return `
                        <li class="suggestion-item">
                            <i class="fas fa-search"></i>
                            <span class="suggestion-text">${item.text}</span>
                            <span class="suggestion-count">${formatCount(item.count)}</span>
                        </li>
                    `;
                }).join('');

                // 添加事件监听
                document.querySelectorAll('#suggestions-list .suggestion-item').forEach(item => {
                    const text = item.querySelector('.suggestion-text').textContent;
                    item.addEventListener('click', () => performSearch(text));
                });

                // 显示建议容器
                suggestionsContainer.style.display = 'block';
                renderHistoryList();

            } catch (error) {
                console.error('获取建议出错:', error);
                suggestionsList.innerHTML = '<li class="suggestion-item"><i class="fas fa-exclamation-triangle"></i><span>无法获取建议</span></li>';
            }
        }

        // 执行搜索
        async function performSearch(query) {
            if (!query.trim()) {
                // 显示初始状态
                resultsContainer.innerHTML = `
                    <div class="empty-results">
                        <i class="fas fa-search"></i>
                        <h3>开始您的搜索之旅</h3>
                        <p>输入关键词，探索海量优质商品</p>
                    </div>
                `;
                return;
            }

            // 更新搜索框
            searchInput.value = query;

            // 隐藏建议
            suggestionsContainer.style.display = 'none';

            // 添加到历史记录
            addToSearchHistory(query);

            // 显示加载状态
            resultsContainer.innerHTML = `
                <div class="empty-results">
                    <i class="fas fa-spinner fa-spin"></i>
                    <h3>搜索中...</h3>
                    <p>正在为您查找"${query}"的相关商品</p>
                </div>
            `;

            try {
                // 调用搜索API
                const response = await fetch(`/search?q=${encodeURIComponent(query)}`);
                const products = await response.json();
                displayResults(products, query);
            } catch (error) {
                console.error('搜索出错:', error);
                resultsContainer.innerHTML = `
                    <div class="empty-results">
                        <i class="fas fa-exclamation-triangle"></i>
                        <h3>搜索服务暂时不可用</h3>
                        <p>请稍后再试或联系客服</p>
                    </div>
                `;
            }
        }

        // 显示搜索结果
        function displayResults(products, query) {
            if (products.length === 0) {
                resultsContainer.innerHTML = `
                    <div class="empty-results">
                        <i class="fas fa-search"></i>
                        <h3>没有找到相关商品</h3>
                        <p>没有找到与"${query}"匹配的商品</p>
                        <p>请尝试其他关键词</p>
                    </div>
                `;
                return;
            }

            resultsContainer.innerHTML = products.map((product, index) => {
                const isHot = product.sales > 20000;
                const isNew = index < 3;

                return `
                    <div class="product-card">
                        ${isHot ? '<div class="product-badge">热卖</div>' : ''}
                        ${isNew ? '<div class="product-badge" style="background:#00c3ff;">新品</div>' : ''}
                        <div class="product-image-container">
                            <img src="${product.image_url}" alt="${product.title}" class="product-image">
                        </div>
                        <div class="product-info">
                            <div class="product-title">${product.title}</div>
                            <div class="product-price">¥${product.price.toFixed(2)}</div>
                            <div class="product-meta">
                                <span>销量: ${formatCount(product.sales)}</span>
                                <span class="product-rating">
                                    <i class="fas fa-star"></i> ${product.rating.toFixed(1)}
                                </span>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 事件监听
        searchInput.addEventListener('input', () => {
            const query = searchInput.value.trim();
            getSearchSuggestions(query);
        });

        searchInput.addEventListener('focus', () => {
            if (searchInput.value.trim()) {
                suggestionsContainer.style.display = 'block';
            } else {
                // 显示历史记录和热门搜索
                renderHistoryList();
                suggestionsList.innerHTML = '<li class="suggestion-item"><i class="fas fa-info-circle"></i><span>输入关键词获取实时建议</span></li>';
                suggestionsContainer.style.display = 'block';
            }
        });

        document.addEventListener('click', (e) => {
            if (!searchInput.contains(e.target) && !suggestionsContainer.contains(e.target)) {
                suggestionsContainer.style.display = 'none';
            }
        });

        searchButton.addEventListener('click', () => {
            performSearch(searchInput.value.trim());
        });

        searchInput.addEventListener('keyup', (e) => {
            if (e.key === 'Enter') {
                performSearch(searchInput.value.trim());
            }
        });

        // 初始化页面
        window.onload = initPage;
    </script>
</body>
</html>